package edu.thu.studio.ormdesigner.editor.figure;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FlowLayout;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.geometry.Insets;

import edu.thu.studio.ormdesigner.model.orm.table.Column;

public class ColumnFigure extends Figure {
    
    public ColumnFigure() {
        FlowLayout layout = new FlowLayout();
        layout.setMinorAlignment(FlowLayout.ALIGN_CENTER);
        this.setLayoutManager(layout);
        
        this.setBorder(new MarginBorder(new Insets(0, 5, 0, 0)));
    }
    
    public void clearLabel() {
        this.removeAll();
    }
    
    public void setColumnName() {
        
    }
    
    public void addColumn(Column column) {
        this.removeAll();
        
        Label label = this.createColumnLabel();
        label.setText(this.getColumnText(column));
        
        this.add(label);
    }
    
    protected Label createColumnLabel() {
        Label label = new Label();
        label.setBorder(new MarginBorder(new Insets(3, 5, 3, 5)));
        label.setLabelAlignment(PositionConstants.LEFT);
        return label;
    }
    
    protected String getColumnText(Column column) {
        StringBuilder text = new StringBuilder();
        text.append(column.getName() + "［" + column.getCode() + "］");
        
        if(null!=column.getDomainObject()){
            text.append(column.getDomainObject().getDataType());
        }else{
            text.append(column.getDataType());
        }
        
        if (column.getMandatory() && column.getPrimary()) {
            text.append(" (UNN)");
            
        } else if (column.getMandatory()) {
            text.append(" (NN)");
            
        } else if (column.getPrimary()) {
            text.append(" (U)");
        }
        
        return text.toString();
    }
    
    @Override
    protected void paintFigure(Graphics graphics) {
        if (graphics.getBackgroundColor().equals(this.getParent().getBackgroundColor())) {
            graphics.setAlpha(0);
        }
        
        super.paintFigure(graphics);
    }
    
}
